<template>
   <div class="query-container">
     <query-form>
       <template v-slot:default="slotProps">
         <el-button type="primary" round icon="el-icon-search" @click="onSubmit(slotProps.sizeForm)">查询</el-button>
         <el-button type="primary" round icon="el-icon-download" @click="onDownLoad">下载</el-button>
       </template>
     </query-form>

     <result-table :tableData="tableData"/>
   </div>
</template>
<script lang="ts">
import {defineComponent, ref} from 'vue'
import {dataType} from "/@/api";
import {errorMessage, successMessage} from "/@/utils/message";
import {queryInformation,downloadInformation} from "/@/api";
import resultTable from './resultTable.vue'
import queryForm from './queryForm.vue'
export default defineComponent({
  name:'',
  components:{
    resultTable,
    queryForm
  },
  setup(){
    const tableData=ref<Array<dataType>>([])

    const onSubmit=async (sizeForm:object)=>{
      try{
        console.log(sizeForm)
        //@ts-ignore
        tableData.value =await queryInformation(sizeForm)
        successMessage('查询成功！')
        //@ts-ignore
      }catch (e) {
        errorMessage('网络错误！')
      }
    }
    const onDownLoad=async ()=>{
      if(tableData.value.length===0){
        errorMessage('请先查询再下载！！')
        return
      }
      try{
        const res:any=await downloadInformation(tableData.value)
        // 创建blob对象
        let blob = new Blob([res], {
          type: "application/vnd.ms-excel;charset=utf-8"
        });
        let url: Blob|string = blob, saveName = '查询结果.xlsx';

        if (typeof url == 'object' && url instanceof Blob) {
          url = URL.createObjectURL(url); // 创建blob地址
        }
        // 创建a标签，用于下载文件
        let aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        let event=null;
        if (window.MouseEvent) event = new MouseEvent('click');
        else {
          event = document.createEvent('MouseEvents');
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0,
              null);
        }
        // 触发a标签的点击事件，从之前定义的blob地址获取二进制流
        aLink.dispatchEvent(event);
        // 移除blob地址
        URL.revokeObjectURL(url)
        successMessage('下载成功！')
        //@ts-ignore
      }catch (e) {
        errorMessage('网络错误！')
      }
    }
    return {
      onSubmit,
      tableData,
      onDownLoad,
    }
  }

})
</script>

<style lang='scss' scoped>
.query-container{
  padding:20px 30px 50px 30px;
  position: relative;
  z-index:-1;
}
</style>
